package reserver

import (
	"context"
	"fiberCommonUtils/request"
	"fmt"
	"github.com/gofiber/fiber/v2"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"mongoDB"
)

func FindOneReserver(ctx context.Context, filter *bson.D, opts ...*options.FindOneOptions) (*Reserver, error) {
	result := new(Reserver)
	err := result.GetCollection().FindOne(ctx, filter, opts...).Decode(result)
	if err != nil {
		return nil, err
	}
	return result, err
}

func decodeReserverCursor(ctx context.Context, cursor *mongo.Cursor) (ReserverList *[]Reserver, err error) {
	list := make([]Reserver, 0)
	err = cursor.All(ctx, ReserverList)
	if err != nil {
		return nil, err
	}
	return &list, err
}

func QueryManyReserver(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (result *[]Reserver, err error) {
	cursor, err := (&Reserver{}).GetCollection().Find(ctx, filter, opts...)
	if err != nil {
		return nil, err
	}
	result, err = decodeReserverCursor(ctx, cursor)
	return result, err
}

func (r *Reserver) FindByID(ctx context.Context, id any, opts ...*options.FindOneOptions) error {
	return r.FindLastOne(ctx, &bson.D{{"_id", id}}, opts...)
}

// FindLastOne /* 查找单个 */
func (r *Reserver) FindLastOne(ctx context.Context, filter *bson.D, opts ...*options.FindOneOptions) error {
	_opt := make([]*options.FindOneOptions, 0)
	for _, opt := range opts {
		_opt = append(_opt, opt)
	}
	_opt = append(_opt, options.FindOne().SetSort(bson.D{{"_id", -1}}))
	return r.GetCollection().FindOne(ctx, *filter, _opt...).Decode(r)
}

type ListReserver []Reserver

// FindMany /* 查找d多个 */
func (list *ListReserver) FindMany(ctx context.Context, filter *bson.D, opts ...*options.FindOptions) error {
	_opt := make([]*options.FindOptions, 0)
	_opt = append(_opt, options.Find().SetSort(bson.D{{"_id", -1}}))
	for _, opt := range opts {
		_opt = append(_opt, opt)
	}
	cursor, err := (&Reserver{}).GetCollection().Find(ctx, *filter, _opt...)
	if err != nil {
		return err
	}
	return cursor.All(ctx, list)
}

// MiddlewareFindReserver 读取预约信息
//
//	c.Locals("reserver").(*Reserver)
//	c.Locals("reserverID").(*primitive.ObjectID)
func MiddlewareFindReserver(c *fiber.Ctx) error {
	ctx, cancel := mongoDB.MongoDBTimeoutContext()
	defer cancel()
	data := request.ParsePostLikeRequestV2(c, &struct {
		ReserverID primitive.ObjectID `json:"reserverID" form:"reserverID"`
	}{})
	_reserver := &Reserver{}
	err := _reserver.FindByID(ctx, data.ReserverID)
	if err != nil {
		return fiber.NewError(500, fmt.Sprint("读取对应排班错误,", err.Error()))
	}
	c.Locals("reserver", _reserver)
	c.Locals("reserverID", &data.ReserverID)
	return c.Next()
}
